﻿Imports CRM.BusinessLayer
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Controls.Primitives
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Shapes
Imports System.Xml
Imports System.IO
Imports System.Data

Partial Public Class frmAdminEmailTemplates
    Private Frm_InsertBookmark As String = String.Empty
    Dim selectedTemplateItem As DataRowView
    Private Sub frmAdminEmailTemplates_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        GeneralTasks.ChangeTheme(Me)
        GeneralTasks.EnumerateandFill(Me.LogicalChildren)
        Call SQL_TemplateList()
    End Sub

    Public Sub SQL_TemplateList()

        Dim StrSQL As String

        StrSQL = "SELECT D_EmailTemplates.EMailTemplate_ID, MAX(D_EmailTemplates.EMailTemplate_Name) AS Title, COUNT(I_SL_SLSMailTemplates.SLSMailTemplate_ID) AS Uses"
        StrSQL = StrSQL & " FROM D_EmailTemplates LEFT OUTER JOIN"
        StrSQL = StrSQL & " I_SL_SLSMailTemplates ON D_EmailTemplates.EMailTemplate_ID = I_SL_SLSMailTemplates.SLSMailTemplate_TemplateID"
        StrSQL = StrSQL & " GROUP BY D_EmailTemplates.EMailTemplate_ID"
        StrSQL = StrSQL & " ORDER BY MAX(D_EmailTemplates.EMailTemplate_Name)"
        Dim templateList As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
        DataBinding.BindListView(templateList, List_Templates)

    End Sub

    Private Sub Btn_AddNew_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_AddNew.Click
        Try
            Me.Txt_Body.Text = String.Empty
            Me.Txt_Subject.Text = String.Empty
            Me.Txt_Title.Text = String.Empty

            Me.Txt_Body.IsEnabled = True
            Me.Txt_Body.IsReadOnly = False
            Me.Txt_Subject.IsEnabled = True
            Me.Txt_Subject.IsReadOnly = False
            Me.Txt_Title.IsEnabled = True
            Me.Txt_Title.IsReadOnly = False

            Me.Txt_Title.Focus()

            Me.Btn_AddNew.IsEnabled = False
            Me.Btn_Delete.IsEnabled = False
            Me.Btn_Edit.IsEnabled = True

            'Me.List_Templates = Null
            Me.List_Templates.IsEnabled = True
            FillBookMarkList()
            Me.List_Bookmarks.IsEnabled = True
            Me.Btn_InsertBookmark.IsEnabled = True
            Me.Txt_CursorPosition.Text = 0

            Me.Btn_Edit.Content = "Save New"
            Me.Btn_Close.content = "Cancel"
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminEmailTemplates-Btn_AddNew_Click")
        End Try

    End Sub
    Private Sub FillBookMarkList()

        Try
            Dim StrSQL As String
            StrSQL = "SELECT Bookmark_ID, Bookmark_Text, Bookmark_Desc, Bookmark_Legacy"
            StrSQL = StrSQL & " FROM I_SL_Bookmarks"
            StrSQL = StrSQL & " WHERE (Bookmark_Legacy = 0)"
            StrSQL = StrSQL & " ORDER BY Bookmark_Text"
            Dim bookmarkList As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL)
            DataBinding.BindListView(bookmarkList, List_Bookmarks)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminEmailTemplates-FillBookMarkList")
        End Try

    End Sub
    Private Sub Btn_Edit_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_Edit.Click
        Dim CommonFuncs As New CommonFuncs
        Try
            Dim StrSQL As String, Rst As DataTable, IntID As Integer, StrMess As String

            Select Case Me.Btn_Edit.Content

                Case "Edit"
                    'Go into Edit mode
                    Me.selectedTemplateItem = Me.List_Templates.SelectedItem
                    If selectedTemplateItem Is Nothing Then
                        MsgBox("Please select the email template to edit.")
                        Exit Sub
                    End If
                    Me.Txt_Body.IsReadOnly = False
                    Me.Txt_Subject.IsReadOnly = False
                    Me.Txt_Title.IsReadOnly = False

                    Me.Btn_Edit.Content = "Save"
                    Me.Btn_Close.Content = "Cancel"

                    Me.Btn_AddNew.IsEnabled = False
                    Me.Btn_Delete.IsEnabled = False

                    Me.List_Templates.IsEnabled = True
                    FillBookMarkList()
                    Me.List_Bookmarks.IsEnabled = True
                    Me.Btn_InsertBookmark.IsEnabled = True
                    Me.Txt_CursorPosition.Text = 0


                Case "Save"
                    'Save edits to existing

                    If Me.Txt_Body.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank body, please amend", , "Error")
                        Me.Txt_Body.Focus()
                        Exit Sub
                    End If

                    If Me.Txt_Subject.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank subject, please amend", , "Error")
                        Me.Txt_Subject.Focus()
                        Exit Sub
                    End If

                    If Me.Txt_Title.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank title, please amend", , "Error")
                        Me.Txt_Title.Focus()
                        Exit Sub
                    End If

                    StrSQL = String.Empty

                    If Me.Txt_Body.Text <> Me.Txt_OldBody.Text Then
                        StrSQL = " EmailTemplate_Body = '" & CommonFuncs.SwapQuotes(Me.Txt_Body.Text.Trim) & "'"

                        StrMess = "Body edited from: " & vbCrLf & "-------------" & vbCrLf & Me.Txt_OldBody.Text & vbCrLf & "-------------" & vbCrLf & "To: " & vbCrLf & "-------------" & Me.Txt_Body.Text & vbCrLf & "-------------"
                    End If

                    If Me.Txt_Subject.Text <> Me.Txt_OldSubject.Text Then
                        If StrSQL <> "" Then
                            StrSQL = StrSQL & ", "
                            StrMess = StrMess & vbCrLf & vbCrLf
                        End If

                        StrSQL = StrSQL & " EMailTemplate_SubjectLine = '" & Me.Txt_Subject.Text & "'"

                        StrMess = StrMess & "Subject changed from:" & vbCrLf & Me.Txt_OldSubject.Text & vbCrLf & "To:" & vbCrLf & Me.Txt_Subject.Text
                    End If

                    If Me.Txt_Title.Text <> Me.Txt_OldTitle.Text Then
                        If StrSQL <> "" Then
                            StrSQL = StrSQL & ", "
                            StrMess = StrMess & vbCrLf & vbCrLf
                        End If

                        StrSQL = StrSQL & " EMailTemplate_Name = '" & Me.Txt_Title.Text & "'"

                        StrMess = StrMess & "Title changed from:" & vbCrLf & Me.Txt_OldTitle.Text & vbCrLf & "To:" & vbCrLf & Me.Txt_Title.Text
                    End If

                    If StrSQL = String.Empty Then
                        Call MsgBox("Nothing changed!")
                        Exit Sub
                    End If

                    StrSQL = "Update D_EmailTemplates set " & StrSQL
                    Dim selectedTemplate As DataRowView = Me.selectedTemplateItem
                    If selectedTemplate Is Nothing Then
                        MsgBox("Select the email template to edit.")
                        Exit Sub
                    End If
                    StrSQL = StrSQL & " WHERE EMailTemplate_ID = " & selectedTemplate(0)

                    If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

                    StrMess = "EMail Template No. " & selectedTemplate(0).ToString() & " (" & Me.Txt_OldTitle.Text & ") edited as follows:" & vbCrLf & vbCrLf & StrMess

                    Call (New TasksEvents).GblFunc_Add_SysEvent("Admin (SL)", StrMess)

                    Me.Txt_Body.IsReadOnly = True
                    Me.Txt_Subject.IsReadOnly = True
                    Me.Txt_Title.IsReadOnly = True

                    Me.Btn_Edit.Content = "Edit"
                    Me.Btn_Close.Content = "Close"

                    Me.Btn_AddNew.IsEnabled = True
                    Me.Btn_Delete.IsEnabled = True

                    Me.List_Templates.IsEnabled = True

                    Me.List_Bookmarks.ItemsSource = Nothing
                    Me.FillBookMarkList()
                    'Me.List_Bookmarks = Null
                    Me.List_Bookmarks.IsEnabled = False
                    Me.Btn_InsertBookmark.IsEnabled = False

                    Call List_Templates_AfterUpdate()

                Case "Save New"
                    'Create New Template
                    If Me.Txt_Body.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank body, please amend", , "Error")
                        Me.Txt_Body.Focus()
                        Exit Sub
                    End If

                    If Me.Txt_Subject.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank subject, please amend", , "Error")
                        Me.Txt_Subject.Focus()
                        Exit Sub
                    End If

                    If Me.Txt_Title.Text.Trim = String.Empty Then
                        Call MsgBox("Cannot have a blank title, please amend", , "Error")
                        Me.Txt_Title.Focus()
                        Exit Sub
                    End If

                    StrSQL = "Select EmailTemplate_Id from D_EMailTemplates where EMailTemplate_Name ='" & Me.Txt_Title.Text.Trim & "'"
                    Rst = CommonDataFunctions.GetSQLDatatable(StrSQL)

                    If Rst.Rows.Count > 0 Then
                        Rst.Dispose()
                        Call MsgBox("There is already an EMail Template with that title, to avoid confusion please chose another for this mail", , "Error")
                        Me.Txt_Title.Focus()
                        Exit Sub
                    End If

                    StrSQL = "Insert Into D_EMailTemplates "
                    StrSQL = StrSQL & " (EMailTemplate_Name, EMailTemplate_SubjectLine, EmailTemplate_Body, EMailTemplate_EnteredBy,EMailTemplate_LetterTypeID,EMailTemplate_Category,EMailTemplate_CustomerType ,EMailTemplate_DTEntered)"
                    StrSQL = StrSQL & " VALUES("
                    StrSQL = StrSQL & " '" & CommonFuncs.SwapQuotes(Me.Txt_Title.Text.Trim) & "',"
                    StrSQL = StrSQL & " '" & CommonFuncs.SwapQuotes(Me.Txt_Subject.Text.Trim) & "',"
                    StrSQL = StrSQL & " '" & CommonFuncs.SwapQuotes(Me.Txt_Body.Text.Trim) & "',"
                    StrSQL = StrSQL & " '" & CommonFuncs.SwapQuotes(GlobalCRM.CurrentConName) & "',0,0,1,getdate())"

                    If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

                    StrSQL = "Select EmailTemplate_ID from D_EmailTemplates where EMailTemplate_Name = '" & Me.Txt_Title.Text.Trim & "'"
                    Rst = CommonDataFunctions.GetSQLDatatable(StrSQL)

                    If Rst.Rows.Count = 0 Then
                        Rst.Dispose()
                        Call MsgBox("Couldn't find new Template!", , "Error")
                        Exit Sub
                    End If

                    IntID = Rst.Rows(0)("EmailTemplate_ID")
                    Rst.Dispose()

                    StrMess = "New EMail Template created, No. " & IntID & " , details bellow"
                    StrMess = StrMess & vbCrLf & vbCrLf & "Title: " & Me.Txt_Title.Text
                    StrMess = StrMess & vbCrLf & "Subject: " & Me.Txt_Subject.Text
                    StrMess = StrMess & vbCrLf & "Body: " & vbCrLf & Me.Txt_Body.Text

                    Call (New TasksEvents).GblFunc_Add_SysEvent("Admin (SL)", StrMess)

                    Me.FillBookMarkList()
                    'Me.List_Templates = IntID

                    Me.Txt_Body.IsReadOnly = True
                    Me.Txt_Subject.IsReadOnly = True
                    Me.Txt_Title.IsReadOnly = True

                    Me.Btn_Edit.Content = "Edit"
                    Me.Btn_Close.Content = "Close"

                    Me.Btn_AddNew.IsEnabled = True
                    Me.Btn_Delete.IsEnabled = True

                    'Me.List_Templates.Content = False

                    'Me.List_Bookmarks.RowSource = ""
                    Me.FillBookMarkList()
                    'Me.List_Bookmarks = Null
                    Me.List_Bookmarks.IsEnabled = False
                    Me.Btn_InsertBookmark.IsEnabled = False

                    Call List_Templates_AfterUpdate()

            End Select

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminEmailTemplates-Btn_Edit_Click")
        Finally
            SQL_TemplateList()
            CommonFuncs = Nothing
        End Try
    End Sub

    Private Sub List_Templates_AfterUpdate()
        Dim StrSQL As String, Rst As DataTable

        Dim selectedTemplate As DataRowView = Me.List_Templates.SelectedItem
        If selectedTemplate Is Nothing Then Exit Sub

        StrSQL = "Select EMailTemplate_Name, EMailTemplate_SubjectLine, EMailTemplate_Body from D_EMailTemplates Where EMailTemplate_ID = " & selectedTemplate(0)

        Rst = CommonDataFunctions.GetSQLDatatable(StrSQL)

        If Rst.Rows.Count = 0 Then
            'Error
            Rst.Dispose()
            Call MsgBox("Mail template not found!")
            Me.Txt_Body.Text = String.Empty
            Me.Txt_Subject.Text = String.Empty
            Me.Txt_Title.Text = String.Empty
            Me.Btn_Edit.IsEnabled = False
            Exit Sub
        End If

        Me.Txt_Body.Text = Rst.Rows(0)("EMailTemplate_Body")
        Me.Txt_Subject.Text = Rst.Rows(0)("EmailTemplate_SubjectLine")
        Me.Txt_Title.Text = Rst.Rows(0)("EMailTemplate_Name")

        Me.Txt_OldBody.Text = Rst.Rows(0)("EMailTemplate_Body")
        Me.Txt_OldSubject.Text = Rst.Rows(0)("EmailTemplate_SubjectLine")
        Me.Txt_OldTitle.Text = Rst.Rows(0)("EMailTemplate_Name")

        Rst.Dispose()

        Me.Btn_Edit.IsEnabled = True
        Me.Btn_Delete.IsEnabled = True
    End Sub

    Private Sub Btn_Delete_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_Delete.Click
        Try

            Dim StrSQL As String, StrMess As String
            Dim selectedTemplate As DataRowView = Me.List_Templates.SelectedItem
            If selectedTemplate(2) > 0 Then
                StrMess = "This Mail template is in use in " & selectedTemplate(2) & " Stock Letter Set(s)."
                StrMess = StrMess & vbCrLf & "If deleted, it will be immediately removed from all Sets." & vbCrLf & vbCrLf
                StrMess = StrMess & "Are you sure you want to delete this EMail template?"
            Else
                StrMess = "Are you sure you want to delete this EMail template?"
            End If

            If MsgBox(StrMess, vbYesNo, "Confirm delete") <> 6 Then Exit Sub

            StrSQL = "Delete from I_SL_SLSMailTemplates where SLSMailTemplate_TemplateID = " & selectedTemplate(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then Exit Sub

            StrSQL = "Delete from D_EmailTemplates Where EMailTemplate_ID = " & selectedTemplate(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = 0 Then Exit Sub

            StrMess = "Email template no. " & selectedTemplate(0).ToString() & " Delted. Details bellow" & vbCrLf & vbCrLf

            StrMess = StrMess & "Title: " & Me.Txt_Title.Text & vbCrLf
            StrMess = StrMess & "Subject: " & Me.Txt_Subject.Text & vbCrLf
            StrMess = StrMess & "Body: " & vbCrLf & Me.Txt_Title.Text

            Call (New TasksEvents).GblFunc_Add_SysEvent("Admin (SL)", StrMess)

            Me.SQL_TemplateList()
            ' Me.List_Templates = Null

            Me.Txt_Body.IsReadOnly = True
            Me.Txt_Subject.IsReadOnly = True
            Me.Txt_Title.IsReadOnly = True

            Me.Btn_Edit.Content = "Edit"
            Me.Btn_Close.Content = "Close"

            Me.Btn_AddNew.IsEnabled = True
            Me.Btn_AddNew.Focus()

            'Me.List_Templates.Content = False

            Me.Txt_Body.Text = ""
            'Call LE(Me.Txt_Body, 0)
            Me.Txt_Subject.Text = ""
            'Call LE(Me.Txt_Subject, 0)
            Me.Txt_Title.Text = ""
            'Call LE(Me.Txt_Title, 0)

            Me.Btn_Edit.IsEnabled = False
            Me.Btn_Delete.IsEnabled = False

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminEmailTemplates -Btn_Delete_Click")
        End Try
    End Sub

    Private Sub Btn_InsertBookmark_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_InsertBookmark.Click
        Try
            If Me.Frm_InsertBookmark = String.Empty Then
                MsgBox("Please click on Either Subject or Body button before pressing Insert BookMark button !")
                Exit Sub
            End If
            Dim StrMess As String
            Dim selecteBookMark As DataRowView = Me.List_Bookmarks.SelectedItem
            If selecteBookMark Is Nothing Then
                Call MsgBox("Please select the bookmark to insert", , "Error")
                Exit Sub
            End If

            If Me.Frm_InsertBookmark = "subject" Then
                If Me.Txt_SLCursorPosition.Text = 0 Then
                    StrMess = " [" & selecteBookMark(1) & "] " & Me.Txt_Subject.Text
                Else
                    StrMess = Microsoft.VisualBasic.Left(Me.Txt_Subject.Text, Me.Txt_SLCursorPosition.Text) & " [" & selecteBookMark(1) & "] "
                    StrMess = StrMess & Right(Me.Txt_Subject.Text, Len(Me.Txt_Subject.Text) - Me.Txt_SLCursorPosition.Text)
                End If

                Me.Txt_Subject.Text = StrMess
            Else
                If Me.Txt_CursorPosition.Text = "body" Then
                    StrMess = " [" & selecteBookMark(1) & "] " & Me.Txt_Body.Text
                Else
                    StrMess = Microsoft.VisualBasic.Left(Me.Txt_Body.Text, Me.Txt_CursorPosition.Text) & " [" & selecteBookMark(1) & "] "
                    StrMess = StrMess & Right(Me.Txt_Body.Text, Len(Me.Txt_Body.Text) - Me.Txt_CursorPosition.Text)
                End If

                Me.Txt_Body.Text = StrMess
            End If

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmAdminEmailTemplates -Btn_InsertBookmark_Click")
        Finally
            Me.Frm_InsertBookmark = String.Empty
        End Try
    End Sub

    Private Sub Toggle23_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Toggle23.Click
        Me.Frm_InsertBookmark = "subject"
        Me.Toggle23.IsEnabled = False
        Me.Toggle24.IsEnabled = True
    End Sub

    Private Sub Toggle24_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Toggle24.Click
        Me.Frm_InsertBookmark = "body"
        Me.Toggle24.IsEnabled = False
        Me.Toggle23.IsEnabled = True
    End Sub

    Private Sub Txt_Body_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Txt_Body.KeyUp

        Me.Txt_CursorPosition.Text = Me.Txt_Body.SelectionStart

    End Sub

    Private Sub Txt_Body_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Txt_Body.MouseUp

        Me.Txt_CursorPosition.Text = Me.Txt_Body.SelectionStart

    End Sub

    Private Sub Txt_Subject_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Txt_Subject.KeyUp
        Me.Txt_SLCursorPosition.Text = Me.Txt_Subject.SelectionStart
    End Sub

    Private Sub Txt_Subject_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Txt_Subject.MouseUp
        Me.Txt_SLCursorPosition.Text = Me.Txt_Subject.SelectionStart
    End Sub

    Private Sub List_Templates_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles List_Templates.SelectionChanged
        List_Templates_AfterUpdate()
        Me.Btn_Edit.Content = "Save"
        Me.Txt_Title.IsReadOnly = False
        Me.Txt_Subject.IsReadOnly = False
        Me.Txt_Body.IsReadOnly = False
        Me.List_Bookmarks.IsEnabled = True
        FillBookMarkList()
        Me.selectedTemplateItem = Me.List_Templates.SelectedItem
        Me.Btn_InsertBookmark.IsEnabled = True
        Me.Btn_Close.Content = "Cancel"
    End Sub

    Private Sub Btn_Close_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Btn_Close.Click
        Try
            If Me.Btn_Close.Content = "Close" Then

                Me.Close()
            Else
                Me.Txt_Body.IsReadOnly = True
                Me.Txt_Subject.IsReadOnly = True
                Me.Txt_Title.IsReadOnly = True

                Me.Btn_Edit.Content = "Edit"
                Me.Btn_Close.Content = "Close"

                Me.Btn_AddNew.IsEnabled = True
                Me.Btn_Delete.IsEnabled = True

                Me.List_Templates.IsEnabled = True

                'Me.List_Bookmarks.RowSource = ""
                'Me.List_Bookmarks = Null
                Me.FillBookMarkList()
                Me.List_Bookmarks.IsEnabled = True
                Me.Btn_InsertBookmark.IsEnabled = False

                If selectedTemplateItem Is Nothing Then
                    Me.Txt_Body.Text = ""

                    Me.Txt_Subject.Text = ""

                    Me.Txt_Title.Text = ""


                    Me.Btn_Edit.IsEnabled = False
                    Me.Btn_Delete.IsEnabled = False

                Else
                    Call List_Templates_AfterUpdate()
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "Frm_InsertBookmark-Btn_Close_Click")
        End Try
    End Sub
End Class
